/**   
 * @Title: LoaderContext.java 
 * CopyRight(c)2010-DMX 
 */
package com.dmx.fw.component.util;

import java.lang.reflect.InvocationTargetException;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dmx.fw.util.GlobalSpringContext;

import org.apache.struts2.ServletActionContext;


/** 
 * @Description: localContext Utils
 * @author: system
 * @date: 2006
 * @version V1.0 
 * 
 */
public class LoaderContext {
	
	/** 
	 * @Fields localContext：ThreadLocal
	 */
	private static final ThreadLocal localContext = new ThreadLocal();
	
	/** 
	 * @Fields context：WebApplicationContext
	 */
	private WebApplicationContext context;
	
	/**
	 * @Description get LoaderContext object
	 * @return LoaderContext
	 */
	public static LoaderContext getLoaderContext() {
		LoaderContext ctx = (LoaderContext) localContext.get();
	    if (ctx == null) {
	      ctx = new LoaderContext();
	      localContext.set(ctx);
	    }
	    return ctx;
	}
	
	/**
	 * @Description initialize LoaderContext
	 * @param context: WebApplicationContext
	 */
	public static void initialize(WebApplicationContext context) {
		LoaderContext ctx = getLoaderContext();
	    ctx.context = context;
	}
	
	/**
	 * @Description destroy LoaderContext
	 */
	public static void destroyed(){
		LoaderContext ctx = (LoaderContext) localContext.get();
		if(ctx!=null){
			ctx.context=null;
			localContext.set(null);
		}
	}
	
	
	
	/**
	 * @Description 获得bean对象，例如：能够为job中进行调用。
	 * @param key
	 * @return
	 */
	public Object getBean(String key){
		WebApplicationContext tmpContext = this.context;
		if(tmpContext==null){
			try{
				tmpContext = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
				//initialize(WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext()));
			}catch(Exception e){
				
			}
			//ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
			if (tmpContext==null){
				tmpContext=(WebApplicationContext)GlobalSpringContext.getApplicationContext();
			}
		}
		return tmpContext.getBean(key);
	}
}
